package com.tbit.uqbike.config.mvc;

import cn.hutool.core.util.StrUtil;
import com.tbit.uqbike.client.dto.CommonHeaderDTO;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

@Component
public class CommonHeaderResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CommonHeader.class) &&
               parameter.getParameterType().equals(CommonHeaderDTO.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) {
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();

        CommonHeaderDTO headerDTO = new CommonHeaderDTO();
        headerDTO.setAppId(request.getHeader("appId"));
        headerDTO.setSessionId(request.getHeader("sessionId"));
        headerDTO.setTraceId(request.getHeader("traceId"));
        if (StrUtil.isNotEmpty(request.getHeader("brandId"))){
            headerDTO.setBrandId(Integer.parseInt(request.getHeader("brandId")));
        }
        if (StrUtil.isNotEmpty(request.getHeader("accountId"))){
            headerDTO.setAccountId(Integer.parseInt(request.getHeader("accountId")));
        }
        return headerDTO;
    }
}